<script setup>
  import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
  import { useRouter } from 'vue-router'
  import * as echarts from 'echarts'
  import { useProvinceWeather } from '@/composables/useProvinceWeather'

  const router = useRouter()
  const mapContainer = ref(null)
  const chartInstance = ref(null)
  const mapLoading = ref(true)
  const error = ref(null)
  const mapData = ref(null)

  // 省份名称映射表
  const provinceNameMap = {
    北京市: '北京',
    天津市: '天津',
    河北省: '河北',
    山西省: '山西',
    内蒙古自治区: '内蒙古',
    辽宁省: '辽宁',
    吉林省: '吉林',
    黑龙江省: '黑龙江',
    上海市: '上海',
    江苏省: '江苏',
    浙江省: '浙江',
    安徽省: '安徽',
    福建省: '福建',
    江西省: '江西',
    山东省: '山东',
    河南省: '河南',
    湖北省: '湖北',
    湖南省: '湖南',
    广东省: '广东',
    广西壮族自治区: '广西',
    海南省: '海南',
    重庆市: '重庆',
    四川省: '四川',
    贵州省: '贵州',
    云南省: '云南',
    西藏自治区: '西藏',
    陕西省: '陕西',
    甘肃省: '甘肃',
    青海省: '青海',
    宁夏回族自治区: '宁夏',
    新疆维吾尔自治区: '新疆',
    台湾省: '台湾',
    香港特别行政区: '香港',
    澳门特别行政区: '澳门'
  }

  const {
    weatherList,
    loading: weatherLoading,
    error: weatherError
  } = useProvinceWeather()

  const loadMap = async () => {
    try {
      const response = await fetch(
        'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json'
      )
      if (!response.ok) throw new Error('地图数据请求失败')

      mapData.value = await response.json()
      if (!mapData.value?.features) throw new Error('地图数据格式错误')

      echarts.registerMap('china', mapData.value)
      mapLoading.value = false
    } catch (err) {
      error.value = `地图加载失败: ${err.message}`
      mapLoading.value = false
      console.error('地图加载错误:', err)
    }
  }

  const initMap = () => {
    if (!mapContainer.value || !mapData.value || !weatherList.value?.length)
      return

    try {
      chartInstance.value = echarts.init(mapContainer.value)

      // 准备地图数据
      const mapSeriesData = mapData.value.features.map(feature => {
        const rawName = feature.properties.name
        const provinceName = provinceNameMap[rawName] || rawName
        const weatherInfo =
          weatherList.value.find(item => item.province === provinceName) || {}

        return {
          name: rawName,
          value: Number(weatherInfo.temp) || 20,
          weather: weatherInfo.weather || '未知',
          province: provinceName
        }
      })

      // 温度范围计算
      const temps = mapSeriesData
        .map(item => item.value)
        .filter(Number.isFinite)
      const minTemp = temps.length ? Math.min(...temps) : 0
      const maxTemp = temps.length ? Math.max(...temps) : 40

      const option = {
        backgroundColor: '#f5f7fa',
        title: {
          text: '中国各省份天气分布图',
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: params => {
            return `
            <div style="
              padding: 8px;
              background: rgba(255,255,255,0.95);
              border-radius: 4px;
              box-shadow: 0 2px 8px rgba(0,0,0,0.1);
              min-width: 120px;
            ">
              <div style="
                font-size: 14px;
                color: #333;
                font-weight: 600;
                margin-bottom: 6px;
              ">${params.data.province}</div>
              <div style="
                display: flex;
                flex-direction: column;
                gap: 4px;
                font-size: 12px;
                color: #666;
              ">
                <span>天气：${params.data.weather}</span>
                <span>温度：${params.data.value}℃</span>
              </div>
            </div>
          `
          }
        },
        visualMap: {
          min: minTemp,
          max: maxTemp,
          text: ['高温', '低温'],
          left: 'right',
          top: 'bottom',
          calculable: true,
          inRange: {
            color: [
              '#313695',
              '#4575b4',
              '#74add1',
              '#abd9e9',
              '#e0f3f8',
              '#ffffbf',
              '#fee090',
              '#fdae61',
              '#f46d43',
              '#d73027',
              '#a50026'
            ]
          },
          textStyle: {
            color: '#666'
          },
          formatter: value => `${value}℃`
        },
        series: [
          {
            name: '温度',
            type: 'map',
            map: 'china',
            roam: true,
            zoom: 1.2,
            label: {
              show: true,
              fontSize: 12,
              color: '#333',
              fontWeight: 'bold',
              textBorderColor: '#fff',
              textBorderWidth: 2,
              formatter: '{b}'
            },
            emphasis: {
              label: {
                show: true,
                color: 'orange',
                fontSize: 14
              },
              itemStyle: {
                areaColor: '#ff69b4',
                borderColor: '#fff'
              }
            },
            itemStyle: {
              areaColor: '#f7f8fa',
              borderColor: '#ccc',
              borderWidth: 0.5
            },
            data: mapSeriesData
          }
        ]
      }

      chartInstance.value.setOption(option)

      // 添加点击事件监听
      chartInstance.value.on('click', 'series', params => {
        handleProvinceClick(params.data.province)
      })

      window.addEventListener('resize', handleResize)
    } catch (err) {
      error.value = `图表初始化失败: ${err.message}`
      console.error('图表初始化错误:', err)
    }
  }

  // 省份点击处理
  const handleProvinceClick = provinceName => {
    router.push({
      path: `/province/${encodeURIComponent(provinceName)}`
    })
  }

  const handleResize = () => {
    chartInstance.value?.resize()
  }

  onMounted(() => {
    loadMap()
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    chartInstance.value?.dispose()
  })

  watch(
    [() => mapData.value, () => weatherList.value],
    ([newMapData, newWeatherList]) => {
      if (newMapData && newWeatherList?.length) {
        initMap()
      }
    }
  )
</script>

<template>
  <div class="weather-map-container">
    <div v-if="mapLoading" class="loading">地图加载中...</div>
    <div v-if="weatherLoading" class="loading">天气数据加载中...</div>
    <div v-if="error" class="error">{{ error }}</div>
    <div v-if="weatherError" class="error">{{ weatherError }}</div>
    <div ref="mapContainer" class="map-container"></div>
  </div>
</template>

<style scoped>
  .weather-map-container {
    width: 100%;
    height: 100%;
    padding: 20px;
    box-sizing: border-box;
  }

  .map-container {
    width: 100%;
    height: 700px;
    border: 1px solid #eee;
    border-radius: 8px;
    margin-top: 16px;
    background: #fff;
  }

  .loading,
  .error {
    padding: 20px;
    text-align: center;
    font-size: 16px;
  }

  .loading {
    color: #666;
  }

  .error {
    color: #f56c6c;
    background: #fff2f2;
    border-radius: 4px;
  }

  h2 {
    text-align: center;
    color: #333;
    margin-bottom: 16px;
  }
</style>
